﻿using System;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using Chat.Models.Services;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void refreshFriend(int fid)
        {
            object uid = TokenConnectionCacheStore.GetCachedData("cid:" + Context.ConnectionId);
            if (uid != null)
            {
                if (UserService.GetFriendshipsByUserIDAAndUserB((int)uid, fid) != null)
                {
                    Clients.Client(Context.ConnectionId).refresh();

                    object fcid = TokenConnectionCacheStore.GetCachedData("uid:" + fid);
                    if (fcid != null)
                    {
                        Clients.Client((string)fcid).refresh();
                    }
                }
            }
            else
            {
                Clients.Client(Context.ConnectionId).close();
            }
        }
        public void  auth(string token)
        {
            var session=TokenStore.GetCachedData(token);
            if (session == null)
            {
                Clients.Client(Context.ConnectionId).close();
            }
            else
            {
                TokenConnectionCacheStore.SetCachedData("uid:" + session.UserID, Context.ConnectionId);
                TokenConnectionCacheStore.SetCachedData("cid:"+Context.ConnectionId,session.UserID);
            }
           
        }

        public override Task OnConnected()
        {
           
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {

            object uid = TokenConnectionCacheStore.GetCachedData("cid:" + Context.ConnectionId);
            if (uid != null)
            {
                TokenConnectionCacheStore.RemoveCachedData("uid:" + (int)uid);
                TokenConnectionCacheStore.RemoveCachedData("cid:" + Context.ConnectionId);
            }
            return base.OnDisconnected(stopCalled);
        }

        
    }
}